package com.lesama.lock;

public class ThreadTest2 {
    public static void main(String[] args) {
        Thread t1 = new SellTicketsTask2();
        Thread t2 = new SellTicketsTask2();
        Thread t3 = new SellTicketsTask2();
        t1.setName("线程1");
        t2.setName("线程2");
        t3.setName("线程3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SellTicketsTask2 extends Thread {
    private static int tickets = 2000;

    @Override
    public void run() {
        while (true) {
            // 使用类的字节码对象作为锁对象，因为类的字节码文件只会创建一次
            synchronized (SellTicketsTask2.class) {
                if(tickets == 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "售出了第" + tickets + "张票");
                tickets--;
            }
        }
    }
}
